<template>
  <div>
    <x-header id="header" :left-options="{backText: ''}">我的推广</x-header>
    <div class="main-header">
      <div class="main">
        <div class="spread">
          <div class="spread-qrCode" id="img">
            <img style="height:100%;width:100%;display: block" :src="imageUrl" />
            <canvas id="canvas" class="spread-qrCode-canvas" ></canvas>
          </div>
          <div class="spread-tips">请扫一扫上面的图案我的推广码</div>
        </div>
        <div class="save">
          <x-button class="save-button" plain  @click.native="saveQrcode" >保存到本地</x-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import QRcode from 'qrcode'
export default {
  name: 'spread',
  data () {
    return {
      image: new Image(),
      imageUrl: '',
    }
  },
  methods: {
    saveQrcode() {
      let alink = document.createElement("a");
      alink.href = this.imageUrl;
      alink.download = "loan_qrcode"; //图片名
      alink.click();
    },
    // dataURLtoFile(dataurl, filename) {
    //   let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    //     bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    //   while(n--){
    //     u8arr[n] = bstr.charCodeAt(n);
    //   }
    //   return new File([u8arr], filename, {type:mime});
    // }
  },
  mounted () {
    let canvas = document.querySelector('#canvas');
    let _this = this
    QRcode.toCanvas(canvas, 'sample text',
      { type: "png", width: 270, margin:1 },
      function (error) {
      if (error) console.error(error)
      // console.log_this.imageUrl(canvas.toDataURL("image/png"),base64.encode(canvas.toDataURL("image/png")))
      // _this.image.src = canvas.toDataURL("image/png");
      // let div  = document.getElementById('img');
      // div.appendChild(_this.image);
      _this.imageUrl = canvas.toDataURL("image/png")

    })
  }
}
</script>

<style scoped>
.main {
  overflow: auto;
  background-image: radial-gradient(46% 99%, #F98657 50%, #F14E2C 100%);
  min-height: 100vh;
}
.spread {
  background: #fff;
  display: flex;
  flex-direction: column;
  margin: 1rem auto 6rem;
  padding:2.5rem 1rem 1rem;
  border-radius: 10px;
  width: 19.64rem;
  height: 24.36rem;
}
.spread-qrCode {
  width: 19.64rem;
  height: 19.64rem;
  margin-bottom: 3rem;
}
.spread-qrCode-canvas {
  margin: 0 auto;
  display: block;
  position: fixed;
  right: 999px;
}
.spread-tips {
  text-align: center;
  font-size: 14px;
  color: #A6A6A6;
}
.save {
  width: 90%;
  margin: 0 auto;
}
.save-button {
  color: #fff;
  border-color: #fff;
}
</style>
